package com.qfedu.microcoupon.coupon.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.qfedu.common.core.entity.CouponInfo;
import com.qfedu.common.core.entity.CouponTemplate;
import com.qfedu.common.core.enums.ExpireTypeEnum;
import com.qfedu.common.core.exception.CommonException;
import com.qfedu.common.core.utils.UserUtils;
import com.qfedu.common.redis.utils.RedisCache;
import com.qfedu.microcoupon.coupon.bo.CouponCountInfoBO;
import com.qfedu.microcoupon.coupon.mapper.CouponInfoMapper;
import com.qfedu.microcoupon.coupon.service.CouponInfoService;
import com.qfedu.microcoupon.template.service.CouponTemplateService;
import org.jetbrains.annotations.Nullable;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @Classname CouponInfoServiceImpl
 * @Description TODO
 * @Date 2025-09-25 15:04
 * @Created by 老任与码
 */
@Service
public class CouponInfoServiceImpl implements CouponInfoService {
    @Resource
    private CouponInfoMapper couponInfoMapper;

    @Resource
    private CouponTemplateService couponTemplateService;

    @Resource
    private RedisCache redisCache;

    @Override
    public void distributeCoupon(Integer productType, Integer uid) {
        // Integer uid = UserUtils.getUid();
        List<CouponTemplate> couponTemplates = couponTemplateService.templateByProductType(productType);
        if (couponTemplates != null && couponTemplates.size() > 0) {
            if (productType.equals(1)) {
                CouponTemplate couponTemplate = couponTemplates.get(0);

                // 获取优惠券编码
                String code = getCode(couponTemplate);

                // 根据过期类型，计算领取的优惠券的过期时间
                Date expireDate = getExpireDate(couponTemplate);

                // 添加领取记录
                CouponInfo couponInfo = new CouponInfo();
                couponInfo.setUid(uid);
                couponInfo.setTemplateId(couponTemplate.getId());
                couponInfo.setExpireDate(expireDate);
                couponInfo.setCouponCode(code);
                couponInfoMapper.insert(couponInfo);
            }
        }
    }

    /**
     * 获取优惠券编码，从redis的列表中，或者随机生成
     *
     * @param couponTemplate
     * @return
     */
    private @Nullable String getCode(CouponTemplate couponTemplate) {
        String code = null;
        if (!couponTemplate.getAmount().equals(-1)) {
            // 从redis获取指定模版的编码
            code = redisCache.popCacheList("coupon:template:" + couponTemplate.getId());
            if (code == null) {
                throw new CommonException("优惠券已经领完");
            }
        } else {
            // 如果模版中没有设置优惠券个数，生成优惠券编码的规则：   yyyyMMdd+templateId+随机的6位数字的字符串
            // 需要考虑重复的情况
            String yyyyMMdd = DateUtil.format(couponTemplate.getCreateTime(), "yyyyMMdd");
            code = yyyyMMdd + couponTemplate.getId() + RandomUtil.randomNumbers(6);
        }
        return code;
    }

    /**
     * 设置领取的优惠券的过期时间
     *
     * @param couponTemplate
     * @return
     */
    private @Nullable Date getExpireDate(CouponTemplate couponTemplate) {
        Date expireDate = null;
        Integer expireType = couponTemplate.getExpireType();
        ExpireTypeEnum expireTypeEnum = ExpireTypeEnum.getExpireTypeEnum(expireType);
        switch (expireTypeEnum) {
            case EXPIRE_TEMPLATE:
                expireDate = couponTemplate.getExpire();
                break;
            case EXPIRE_DAYS:
                Calendar calendar = Calendar.getInstance();
                calendar.add(Calendar.DAY_OF_MONTH, couponTemplate.getExpireDays());
                expireDate = calendar.getTime();
                break;
        }
        return expireDate;
    }

    @Override
    public List<CouponCountInfoBO> distributeStatics(List<Integer> templateIds, Integer uid) {
        return couponInfoMapper.selectCountInfo(templateIds, uid);
    }

    @Override
    public void userDistributeCoupon(Integer templateId) {
        Integer uid = UserUtils.getUid();

        CouponTemplate couponTemplate = couponTemplateService.templateInfoById(templateId);

        Long count = couponInfoMapper.selectCount(Wrappers.lambdaQuery(CouponInfo.class)
                .eq(CouponInfo::getUid, uid)
                .eq(CouponInfo::getTemplateId, templateId));

        if (couponTemplate.getLimitNum() <= count) {
            throw new CommonException("该优惠群已经达到领取上限");
        }

        // 计算过期时间
        Date expireDate = getExpireDate(couponTemplate);
        // 获取优惠券编码
        String code = getCode(couponTemplate);

        CouponInfo couponInfo = new CouponInfo();
        couponInfo.setUid(uid);
        couponInfo.setTemplateId(templateId);
        couponInfo.setExpireDate(expireDate);
        couponInfo.setCouponCode(code);
        couponInfoMapper.insert(couponInfo);
    }
}
